package com.guojing.jl.nio.serverscocket;

import com.guojing.jl.nio.util.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BlockServer {

    public static void main(String[] args) throws IOException {

        //使用nio来理解阻塞模式，单线程
        ByteBuffer byteBuffer = ByteBuffer.allocate(100);

        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.bind(new InetSocketAddress(8080));

        //存储所有客户单链接
        List<SocketChannel> allClientChannel = new ArrayList<>();
        while (true) {

            log.info("等待建立客户端链接.........，socketChannel={}",socketChannel);
            //accept建立与客户端的连接，SocketChannel用来与客户端通信： accept是阻塞的
            SocketChannel clientSocket = socketChannel.accept();

            log.info("与客户端链接建立成功.........，socketChannel={}",socketChannel);

            allClientChannel.add(clientSocket);

            for (SocketChannel channel : allClientChannel) {
                //读取客户端发送的数据
                log.info("读取客户端发送的数据，channel={}",channel);

                //read也是阻塞的，没有数据的时候会等待
                channel.read(byteBuffer);

                byteBuffer.flip();
                ByteBufferUtil.debugRead(byteBuffer);
                byteBuffer.clear();
                log.info("读取客户端发送的数据完毕, channel={}",channel);
            }



        }
    }
}
